<?php

// 上次订单
class GoodsorderAction extends UserAction
{
    //魔术方法
    public function __construct()
    {
        parent::__construct();
    }

    //订单列表
    public function index()
    {
        $where['user_id'] = $this->uid;
        if (isset($_REQUEST['order_state'])) {
            if ($_REQUEST['order_state'] != 'all') {
                if ($_REQUEST['order_state'] == 3) {//已完成
                    $where['pay_status'] = 2;// 支付状态；0，未付款；1，付款中 ；2，已付款
                    // $where[''] = 2;//商品配送情况，0，未发货； 1，已发货；2，已收货；3，备货中
                    //退货的也在已完成
                    $where['_string'] = "shipping_status=2 or (shipping_status=1 and order_status in ('2','3','4'))";//订单状态。0，未确认；1，已确 认；2，已取消；3，无效；4，退货；
                } else if ($_REQUEST['order_state'] == 1) {
                    $where['pay_status'] = 2;// 支付状态；0，未付款；1，付款中 ；2，已付款
                    $where['shipping_status'] = array('in', '0,3');//商品配送情况，0，未发货； 1，已发货；2，已收货；3，备货中
                    $where['order_status'] = array('in', '1,0');//订单状态。0，未确认；1，已确 认；2，已取消；3，无效；4，退货；
                    //$where['shipping_status'] =1;//商品配送情况，0，未发货； 1，已发货；2，已收货；3，备货中
                } else if ($_REQUEST['order_state'] == 2) {
                    $where['pay_status'] = 2;// 支付状态；0，未付款；1，付款中 ；2，已付款
                    $where['shipping_status'] = 1;//商品配送情况，0，未发货； 1，已发货；2，已收货；3，备货中
                    $where['order_status'] = 1;//订单状态。0，未确认；1，已确 认；2，已取消；3，无效；4，退货；
                    //$where['shipping_status'] =1;//商品配送情况，0，未发货； 1，已发货；2，已收货；3，备货中
                } else {
                    $where['pay_status'] = $_REQUEST['order_state'];
                }
            }
        } else {
            $_GET['order_state'] = 'all';
        }
        $where['user_del'] = 0;
        $p = $_REQUEST['p'];
        $pagesize = 10;
        $p = !empty($p) ? $p : 1;
        $start = ($p - 1) * $pagesize;
        $field = "order_id,order_sn,order_status,shipping_status,pay_status,goods_amount,order_amount,shipping_fee,add_time,consignee,mobile,address,is_upgrade,share_uid";
        $order_model = M('g_order_info');
        $list = $order_model->where($where)//
        ->field($field)->limit($start, $pagesize)->order('order_id desc')->select();
        // echo $order_model->getlastsql();die;
        //订单状态。0，未确认；1，已确 认；2，已取消；3，无效；4，退货；--order
        //商品配送情况，0，未发货； 1，已发货；2，已收货；3，备货中---shipping
        //支付状态；0，未付款；1，付款中 ；2，已付款----pay
        //待付款 0.0.(0,1)  待发货 0.0.2 待收货0.(1,3).2 已完成1.2.2 退货/返修
//        var_dump($list);die;
        //$order_state = array('0' => '已取消', '10' => '待付款', '20' => '已付款', '30' => '已完成');
        $order_state =array('0' => '已取消', '1' => '待付款', '2' => '待发货','3'=>'已发货', '4' => '已完成');
        $g_order_refund = M('g_order_refund');

        foreach ($list as $key => $value) {
            $order_goods = M('g_order_goods')->field('rec_id,goods_name,goods_image,goods_price,goods_id,yes_refund,is_refund,is_upgrade,goods_number')
                ->where(array('order_id' => $value['order_id']))->select();

            $order_show = $this->get_order_status($value);
            $list[$key]['order_state'] = $order_show['code'];
            $list[$key]['order_state_name'] = $order_show['name'];
            $list[$key]['add_time'] = date("Y/m/d", $value['add_time']);
            $list[$key]['goods'] = $order_goods;
            $list[$key]['is_refund'] = 0;///该订单是否可退货
            $list[$key]['rec_id'] = 0;///该订单是否可退货产品
            //
            $num=0;
            foreach ($order_goods as $k=>$v){
                $num+=$v['goods_number'];
            }
            $list[$key]['num']=$num;
            $list[$key]['order_amount'] += $list[$key]['shipping_fee'];
            $list[$key]['ref_all'] = 0;
			$store_id=$list[$key]['share_uid'];
			$list[$key]['store_name']=M('member')->where('id='.$store_id)->getField('member_name');
            $countgoods = 0;
            if ($order_show['code'] == 'delivered') {
                foreach ($order_goods as $keys => $val) {
                    if ($val['is_refund']) {//可退货
                        if (empty($val['yes_refund'])) {//未退货
                            $list[$key]['is_refund'] = 1;///该订单是否可退货
                            $countgoods++;
                            $list[$key]['rec_id'] = $val['rec_id'];///该订单可退货产品
                            if ($countgoods > 1) {
                                $list[$key]['rec_id'] = 0;///包含2个产品 取消快捷连接
                            }
                        }
                    }
                }
                $f_where = array();
                $f_where['order_id'] = $value['order_id'];
				$f_where['refund_status'] = array('neq','4 and 5');
                $list[$key]['ref_all'] = $g_order_refund->where($f_where)->count();
            }

        }

        if (IS_AJAX) {
            echo json_encode($list);
            die;
        }
        $this->list = $list;
        $where = array();
        $where['user_del'] = 0;
        $where['user_id'] = $this->uid;
        $this->count = $order_model->where($where)->count();
        $where = array();
        $where['user_del'] = 0;
        $where['user_id'] = $this->uid;
        $where['pay_status'] = '0';//代付款
        $this->count00 = $order_model->where($where)->count();
        $where = array();
        $where['user_del'] = 0;
        $where['user_id'] = $this->uid;
        $where['pay_status'] = '2';//待发货
        $where['shipping_status'] = array('in', '0,3');
        $where['order_status'] = array('in', '1,0');//订单状态。0，未确认；1，已确 认；2，已取消；3，无效；4，退货；
        $this->count10 = $order_model->where($where)->count();
        $where = array();
        $where['user_del'] = 0;
        $where['user_id'] = $this->uid;
        $where['pay_status'] = 2;// 支付状态；0，未付款；1，付款中 ；2，已付款
        $where['shipping_status'] = 1;//商品配送情况，0，未发货； 1，已发货；2，已收货；3，备货中
        $where['order_status'] = 1;//订单状态。0，未确认；1，已确 认；2，已取消；3，无效；4，退货；
        $this->count20 = $order_model->where($where)->count();
        $where = array();
        $where['user_del'] = 0;
        $where['user_id'] = $this->uid;
        $where['pay_status'] = '2';//已完成
        //$where['shipping_status'] = '2';
        $where['_string'] = "shipping_status=2 or (shipping_status=1 and order_status in ('2','3','4'))";//订单状态。0，未确认；1，已确 认；2，已取消；3，无效；4，退货；
        $this->count30 = $order_model->where($where)->count();
        $this->webtitle = "FG峰购";
        $this->display();

    }

    //订单信息
    public function order_detail(){
        $memberinfo_de = $this->getMemberDetail();
        $memberinfo_de['balance'] += $memberinfo_de['balance_give'];
        $this->MemberDetail = $memberinfo_de;
        $balance = $memberinfo_de['balance'];
        $balance = sprintf("%.2f", substr(sprintf("%.3f", $balance), 0, -2));
        $this->balance = $balance;
        $menuwhere["order_id"] = array("eq", $_GET["id"]);
        $menuwhere['user_id'] = $this->uid;
        $data = M("g_order_info")->where($menuwhere)->find();

        if ($data) {
            if($data['pay_name']=='alipay'){
                $data['payment']='支付宝支付';
            }else{
                $data['payment']='微信支付';
            }
            $order_goods = M('g_order_goods')->where(array('order_id' => $data["order_id"]))->select();
            if ($order_goods) {
                foreach ($order_goods as $key => $value) {
                    if($value['is_refund']){
                        $f_where = array();
                        $f_where['order_goods_id'] = $value['rec_id'];
                        $refund = M('g_order_refund')->where($f_where)->find();
                        if($refund){
							$refund = $this->get_refund_status($refund);
							$order_goods[$key]['code_name'] = $refund['code_name'];
                        }else{
							$order_goods[$key]['code_name'] = "售后申请中";
                        }
                    }
                }
            }
            $offline_money = 0;

            if ($order_goods) {
                foreach ($order_goods as $key => $value) {
                    if ($value['offline']) {
                        $offline_money = $offline_money + $value['goods_number'] * $value['goods_price'];
                    }
                }
            }

			$this->order_goods = $order_goods;
			$order_show = $this->get_order_status($data);
			if ($data['order_amount'] == $offline_money) {
				$offline_money = $offline_money + $data['shipping_fee'];
			}
			$data['order_amount'] = $data['order_amount'] + $data['shipping_fee'];
			$online_money = $data['order_amount'] - $data['surplus'] - $offline_money;
			$this->online_money = $online_money;
			if ($online_money < 0) {///已经支付过了 不能货到付款
				$offline_money = 0;
			}
			$this->offline_money = $offline_money;

			$this->order_goods = $order_goods;
			$order_show = $this->get_order_status($data);
			$data['order_state'] = $order_show['code'];
			$data['order_state_name'] = $order_show['name'];
			if($data['order_state'] == "delivered"){
				$f_where = array();
				$f_where['order_id'] = $data['order_id'];
				$f_where['refund_status'] = array('neq', '10');
				$this->ref_all = M('g_order_refund')->where($f_where)->count();
			}
			$data = $this->get_order_msg_data($data);////订单显示信息
        }

		// 支付状态；0，未付款；1，付款中 ；2，已付款
		$pay_status = array('0' => '未付款', '1' => '已支付', '2' => '已付款', '100'=>'等待买家付款', '101'=>'已支付，对账中', '102'=>'支付已完成');
		$this->pay_status = $pay_status;
		//商品配送情况，0，未发货； 1，已发货；2，已收货；3，备货中
		$shipping_status = array('0' => '未发货', '1' => '已发货', '2' => '已完成', '3' => '备货中');
		$this->shipping_status = $shipping_status;
		//订单状态。0，未确认；1，已确 认；2，已取消；3，无效；4，退货；
		$this->order_status = array('0' => '未确认', '1' => '已确认', '2' => '已取消', '3' => '无效', '4' => '退货');
		$title = "订单信息";
		$this->assign("data", $data);
		$this->display();
    }

 //订单支付信息
	public function order_pay()
	{
		$memberinfo_de = $this->getMemberDetail();
		$memberinfo_de['balance'] += $memberinfo_de['balance_give'];
		$this->MemberDetail = $memberinfo_de;
		$balance = $memberinfo_de['balance'];
		$balance = sprintf("%.2f", substr(sprintf("%.3f", $balance), 0, -2));
		$this->balance = $balance;//账户余额
		$this->points = (int)$memberinfo_de['points']; //账户积分

		$menuwhere["order_sn"] = array("eq", $_GET["pay_sn"]);
		$menuwhere['user_id'] = $this->uid;
		$data = M("g_order_info")->where($menuwhere)->find();

		if ($data) {
			if($data['pay_name']=='alipay'){
				$data['payment']='支付宝支付';
			}else{
				$data['payment']='微信支付';
			}
			$order_goods = M('g_order_goods')->where(array('order_id' => $data["order_id"]))->select();
			$offline_money = 0;
			if ($order_goods) {
				foreach ($order_goods as $key => $value) {
					if ($value['offline']) {
						$offline_money = $offline_money + $value['goods_number'] * $value['goods_price'];
					}
				}
			}
			$this->order_goods = $order_goods;
			$order_show = $this->get_order_status($data);
			if ($data['order_amount'] == $offline_money) {
				$offline_money = $offline_money + $data['shipping_fee'];
			}
			$data['order_amount'] = $data['order_amount'] + $data['shipping_fee'];

			$online_money = $data['order_amount'] - $data['surplus'] - $offline_money;
			$this->online_money = $online_money;
			if ($online_money < 0) {///已经支付过了 不能货到付款
				$offline_money = 0;
			}
			$this->offline_money = $offline_money;

			$data['order_state'] = $order_show['code'];
			$data['order_state_name'] = $order_show['name'];
			if ($data['order_state'] == "delivered") {
				$f_where = array();
				$f_where['order_id'] = $data['order_id'];
				$f_where['refund_status'] = array('neq', '10');
				$this->ref_all = M('g_order_refund')->where($f_where)->count();
			}
			$data = $this->get_order_msg_data($data);////订单显示信息

		}
		// 支付状态；0，未付款；1，付款中 ；2，已付款
		$pay_status = array('0' => '未付款', '1' => '已支付', '2' => '已付款', '100'=>'等待买家付款', '101'=>'已支付，对账中', '102'=>'支付已完成');
		$this->pay_status = $pay_status;
		//商品配送情况，0，未发货； 1，已发货；2，已收货；3，备货中
		$shipping_status = array('0' => '未发货', '1' => '已发货', '2' => '已完成', '3' => '备货中');
		$this->shipping_status = $shipping_status;
		//订单状态。0，未确认；1，已确 认；2，已取消；3，无效；4，退货；
		$this->order_status = array('0' => '未确认', '1' => '已确认', '2' => '已取消', '3' => '无效', '4' => '退货');

		$title = "订单信息";
		$this->assign("data", $data);
		$this->display();
	}

    //订单显示信息
    public function get_order_msg_data($data = array())
    {
        if (empty($data)) {
            return $data;
        }
        switch ($data['discount_type']) {
            case '1':
                $data['discount_name'] = '抽奖';
                break;

            default:
                # code...
                break;
        }
        $time = time();
        $data['order_amount_all'] = $data['order_amount'];
        $data['discount_price'] = $data['discount'];
        if ($data['pay_status'] == 2) {
            $data['order_amount'] = PriceFormat(floatval($data['order_amount']) - floatval($data['discount']));
        } else {
            if ($data['discount_start_time'] <= $time && $data['discount_end_time'] >= $time) {
                $data['order_amount'] = PriceFormat(floatval($data['order_amount']) - floatval($data['discount']));
            } else {
                $data['discount_price'] = 0;
            }
        }

        return $data;
    }

    ///服务 订单提交
    public function set_order()
    {
        $return_data['status'] = 0;
        $cart_id = $_REQUEST['cart_id'];
        $address_id = $_REQUEST['address_id'];
        $discount = $_REQUEST['discount'];
        $uid = $_SESSION['member']['uid'];
        //购买开关
        $buy_switch = M('sys_param')->where(array('param_code' => 'buy_switch'))->getField('param_value');
        if (empty($buy_switch)) {
            $return_data['error'] = '管理员已关闭交易';
            echo json_encode($return_data);
            die;
        }

        if (empty($address_id)) {
            $return_data['error'] = '请选择收货地址';
            echo json_encode($return_data);
            die;
        }
        $address = M('g_user_address')->where(array('address_id' => $address_id, 'user_id' => $uid))->find();
        if (empty($address)) {
            $return_data['error'] = '收货地址不存在';
            echo json_encode($return_data);
            die;
        }
        $cart_model = D('Cart');
        if ($discount) {
            $discount_msg = $cart_model->get_member_discount_one($discount, $uid);
            if (empty($discount_msg)) {
                $return_data['error'] = '该折扣已过期';
                echo json_encode($return_data);
                die;
            }
        }

        //$where['session_id']=session('session_id');
        $where['user_id'] = $uid;
        $where['rec_id'] = array('in', $cart_id);
        $list = $cart_model->getCartAll($where);

        //计算价格
        $list = $cart_model->getCartSettlement($list);
        if (empty($list['status'])) {
            $return_data['error'] = $list['error'];
            echo json_encode($return_data);
            die;
        }
        $goods = $list['goods_list'];

        $time = time();
        $pay_sn = makePaySn($uid);
        $order_data['order_sn'] = $pay_sn;
		$member = $this->getMemberInfo();
		if($member['member_vip_type']>0){
			$share_uid=$this->uid;
		}else{
			$share_uid=M('member')->where('member_card="'.$this->shop_code.'"')->getField('id');
		}
		$order_data['share_uid'] =$share_uid;
        $order_data['user_id'] = $uid;
		$order_data['is_rebate'] = 0;//订单才生成，没有执行返利操作
        $order_data['consignee'] = $address['consignee'];
        $order_data['province'] = $address['province'];
        $order_data['city'] = $address['city'];//
        $order_data['district'] = $address['area'];//
        $order_data['address'] = $address['address_name'] . $address['address'];//用户消费时的折扣
        $order_data['zipcode'] = $address['zipcode'];//用户消费时的返利折扣
        $order_data['tel'] = $address['tel'];//
        $order_data['mobile'] = $address['mobile'];//
        $order_data['email'] = $address['email'];//
        $order_data['best_time'] = $address['best_time'];//收货人的最佳送货时间
        $order_data['sign_building'] = $address['sign_building'];//收货人的地址的标志性建筑

        $order_data['is_gift'] = $list['is_gift'];//活动类型0 无 1 限时抢购

        $order_data['goods_amount'] = $list['tolal'];//商品总金额
        $order_data['order_amount'] = $list['need_pay'];//应付款金额

        //记录折扣信息
        if ($discount_msg && $discount_msg['discount'] > 0 && $discount_msg['discount'] < 1) {
            $order_data['discount_type'] = $discount_msg['type'];//折扣类型 1 抽奖
            $order_data['discount'] = $list['need_pay'] - $list['need_pay'] * $discount_msg['discount'];//discount 折扣金额
            $order_data['discount_val'] = $discount_msg['discount'];//折扣
            $order_data['discount_start_time'] = $discount_msg['start_time'];
            $order_data['discount_end_time'] = $discount_msg['end_time'];
        }
        /*        if ($list['need_pay'] < 68) {
                    $order_data['shipping_fee'] = 10;//订单金额小于 68 须支付运费10元
                }*/
        $order_data['add_time'] = $time;

        $order_pay_data['buyer_id'] = $uid;
        $order_pay_data['pay_sn'] = $pay_sn;


        $order_model = M('g_order_info');
        $order_goods_model = M('g_order_goods');
        $order_pay_model = M('g_order_pay');

        $order_model->startTrans();//开起事务
        $order_goods_model->startTrans();//开起事务
        $order_pay_model->startTrans();//开起事务

        $add_order = $order_model->add($order_data);
        if ($add_order === false) {
            $return_data['error'] = "订单生成失败，请稍后再试.";
            $order_model->rollback();//回滚事务
            $order_goods_model->rollback();//回滚事务
            $order_pay_model->rollback();//回滚事务
            echo json_encode($return_data);
            die;
        }

        $add_order_pay = $order_pay_model->add($order_pay_data);
        $good_list = $goods;
        foreach ($good_list as $key => $value) {
            if ($value['rec_type'] == 1) {
                $value['goods_name'] = '【限时抢购】' . $value['goods_name'];
            }else{
                $value['goods_name'] =  $value['use_vip'] . $value['goods_name'];
            }
            $order_good_data['order_id'] = $add_order;
            $order_good_data['goods_id'] = $value['goods_id'];
            $order_good_data['goods_name'] = $value['goods_name'];//商品名
            $order_good_data['goods_sn'] = $value['goods_sn'];//商品的唯一货号
            $order_good_data['goods_price'] = $value['goods_price'];//商品价格
            $order_good_data['market_price'] = $value['market_price'];//商品价格
            $order_good_data['goods_number'] = $value['goods_number'];//商品数量
            $order_good_data['goods_image'] = $value['goods_img'];//
            $order_good_data['goods_attr_id'] = $value['goods_attr_id'];//商品实际成交价
            $order_good_data['goods_attr'] = $value['goods_attr'];//商家id
            $order_good_data['share_card'] = $value['share_card'];//分享者 card
            $order_good_data['share_money'] = $value['share_money'];//分享返利金额
            $order_good_data['is_refund'] = $value['is_refund'];//是否可退货 1是 0否
            $order_good_data['goods_shipping'] = $value['goods_shipping'];//包邮方式 默认SF顺风包邮
            $order_good_data['shipping_code'] = $value['shipping_code'];//包邮方式code
            $order_good_data['offline'] = $value['offline'];//货到付款
            $order_good_data['is_exchange'] = $value['is_exchange'];////是否可退货 1是 0否
            $order_good_data['is_gift'] = $value['rec_type'];//活动类型0 无 1 限时抢购
            $order_good_data['promote_start_date'] = $value['promote_start_date'];
            $order_good_data['promote_end_date'] = $value['promote_end_date'];
            $add_order_goods[] = $order_goods_model->add($order_good_data);

        }
        $add_order_goods = array_unique($add_order_goods);//去重
        //in_array如果设置该参数为 true，则检查搜索的数据与数组的值的类型是否相同。
        if ($add_order !== false && $add_order_pay !== false && in_array(false, $add_order_goods, true) === false) {
            $return_data['status'] = 1;
            $order_model->commit();//提交事务
            $order_goods_model->commit();//提交事务
            $order_pay_model->commit();//提交事务
            //记录订单日志
            $data = array();
            $data['order_id'] = $add_order;
            $data['order_amount'] = $list['need_pay'];
            M('g_pay_log')->add($data);
            //记录订单日志
            $data = array();
            $data['order_id'] = $add_order;
            $data['log_role'] = 'buyer';
            $data['log_msg'] = '用户下单成功';
            $data['log_orderstate'] = '10';
            $insert = D('Mallorder')->addOrderLog($data);

            $return_data['pay_sn'] = $pay_sn;
            //删除购物车
            // $del_where['session_id']=session('session_id');
            $del_where = array();
            $del_where['user_id'] = $uid;
            $del_where['rec_id'] = array('in', $cart_id);
            M('g_cart')->where($del_where)->delete();
        } else {
            $order_model->rollback();//回滚事务
            $order_goods_model->rollback();//回滚事务
            $order_pay_model->rollback();//回滚事务
            $return_data['error'] = "订单生成失败，请稍后再试.";
        }
        echo json_encode($return_data);
        die;
    }


    //确认收货
    public function order_delivered()
    {
        $return_data['status'] = 0;
        $o_where["order_id"] = array("eq", $_POST["order_id"]);
        $o_where['user_id'] = $this->uid;
        $data_info = M("g_order_info")->where($o_where)->find();
        if (empty($data_info)) {
            $return_data['error'] = "该订单不存在";
            echo json_encode($return_data);
            die;
        }
        $order_show = $this->get_order_status($data_info);

        if ($order_show['code'] != 'delivered') {//已发货
            $return_data['error'] = "订单状态错误";
            echo json_encode($return_data);
            die;
        }
        $refund = M('g_order_refund')->where(array('member_id' => $data_info['user_id'], 'order_id' => $data_info['order_id']))->find();
        if (!empty($refund) && $refund['refund_status'] != '10') {//
            $return_data['error'] = "订单已退货不能确认";
            echo json_encode($return_data);
            die;
        }
        $model_order = D('Mallorder');
        //查询商家信息
        $model_order->startTrans();
        //更改订单状态
        $data = array();
        $data['shipping_status'] = 2;
        $data['finnshed_time'] = time();
        $order_res = $model_order->editOrder($data, $o_where);

        //记录商家日志
        if ($order_res !== false) {
            //记录订单日志
            $data = array();
            $data['order_id'] = $data_info['order_id'];
            $data['log_role'] = 'buyer';
            $data['log_msg'] = '订单确认收货';
            $data['log_orderstate'] = '40';
            $insert = $model_order->addOrderLog($data);

            ///用户返利 返积分 认证等
			if($data_info['is_upgrade'] == 0){
				$ress = $this->set_member_exchange($data_info);///用户 返利等操作
				// D('Rebate')->set_member_exchange($data_info);
			}
            $model_order->commit();
            $return_data['error'] = "操作成功";
            $return_data['status'] = 1;
            echo json_encode($return_data);
            die;
        } else {
            $model_order->rollback();
            $return_data['error'] = "操作失败";
            echo json_encode($return_data);
            die;
        }
    }
	
	   /*
	*
	* 利润分配
	* $data_info array：订单信息，必须包括order_id , int：order_id;
	* 返回 status 0错误（msg）为错误信息 1成功
	* kkxx 2016-10-08 
	*/
    private function set_member_exchange($data_info = array()){
		$ret = array();
		$ret['status'] = 0;
		
		if(is_array($data_info)){
			$order_id = $data_info['order_id'];
		}else{
			$order_id = $data_info;
		}
		if(!$order_id){
			$ret['msg'] = '参数错误！';
            return $ret;
		}
		$g_order_info = M('g_order_info');
		// $order_info = $g_order_info->where(array('order_id'=>409))->find();
		$order_info = $g_order_info->where(array('order_id'=>$order_id))->find();
        if (empty($order_info)){
			$ret['msg'] = '没有找到订单';
            return $ret;
        }
		
		if($order_info['pay_status'] != 2){
			$ret['msg'] = '订单没有付款';
            return $ret;
		}
		
		$pre = C('DB_PREFIX');//表前缀
		
        //用户自己返利  用户积分增加  返利日志 积分增加日志
		$field = 'mem.id, mem.member_card, mem.mobile, mem.recommend_code, mem.indirect_recommend_code, mem.indirect2_recommend_code, mem.member_status, mem.member_vip_type, mem.member_vip_order, md.provinceid, md.cityid, md.areaid, md.relevel, md.repath';
        $member_info = M()->table($pre . 'member mem')
		->join($pre . 'member_detail md on mem.id=md.member_id')
		->where(array('mem.id' => $order_info['user_id']))
		->field($field)->find();
		
		//shop_rebate_status  123 级返利状态 1 返利  0不返
        $shop_rebate_status = 0;//返利类型 1分享返利 0正常返利(123级返利) 2升级返利
        $member_tuijian_data = array();//返利记录
		
        $order_save_data = array();//订单返利 数据
        $order_save_data['profit_type'] = 0;//返利类型 1分享返利 0正常返利(123级返利)
        $order_save_data['order_profit'] = $order_info['order_amount'];//订单利润= 应付款金额-订单返利
        $order_save_data['order_rebate'] = 0;//订单返利金额
		
		//订单利润
		$is_income = TRUE;
		$money = 0; $c_money = 0; $syb_money = 0;
		if($order_info['is_upgrade'] == 1){
			$level_order = M('member_level_order')->where(array('id'=>$order_info['order_sn']))->find();
			if($level_order['last_level'] > 0){
				$is_income = FALSE;
			}
			$shop_rebate_status = 2;
			$money = $order_info['goods_amount'];
			$syb_money = $order_info['goods_amount'];
		}else{
			$order_goods_info=M('g_order_goods')->where('order_id='.$order_info['order_id'])->select();
			foreach ($order_goods_info as $k=>$v){
				$goods_id=$v['goods_id'];
				$goods_number=$v['goods_number'];
				$goods_price=$v['goods_price'];
				$purchase_price=M('g_goods')->where("goods_id=$goods_id")->getField('purchase_price');
				$money += (($goods_price-$purchase_price)*$goods_number);
			}
			
			$c_money = $money;
		}
		
		if($money <= 0){
			$ret['msg'] = '利润金额错误（'.$money.'）';
			return $ret;
		}
		
		$money_integral = 10;
		//分配比例
		if($order_info['is_upgrade']==1){
			$rem1_money_ratio = 0.28;
			$rem1_integral_ratio = 0.05;
			$rem2_money_ratio = 0.04;
			$rem2_integral_ratio = 0.02;
			$rem3_money_ratio = 0.03;
			$rem3_integral_ratio = 0.01;
		}else{
			$rem1_money_ratio = 0.3;
			$rem1_integral_ratio = 0.1;
			$rem2_money_ratio = 0.08;
			$rem2_integral_ratio = 0.02;
			$rem3_money_ratio = 0.03;
			$rem3_integral_ratio = 0.02;
		}
		$total_ratio = $rem1_money_ratio + $rem1_integral_ratio + $rem2_money_ratio + $rem3_money_ratio + $rem3_integral_ratio;
		
		//推荐人查找
		if($order_info['is_upgrade'] == 0 && $order_info['share_uid'] > 0){ //如果用户的订单推荐人不是原推荐人，利润分配使用订单推荐人的分配路线
			$share_member = M('member')->where(array('id'=>$order_info['share_uid']))->find();
			$share_member_detail = M('member_detail')->where(array('member_id'=>$order_info['share_uid']))->find();
			if(isset($share_member['member_card']) && isset($share_member_detail['repath']) && $share_member['member_card'] != $member_info['recommend_code']){
				$member_info['repath'] = $share_member_detail['repath'].','.$member_info['id'];
				$member_info['relevel'] = $share_member_detail['relevel'] + 1;
			}
		}
		
		$repath = explode(',', $member_info['repath']);
		$member_list_array = M('member')->where(array('id' => array('in', $member_info['repath'])))->select();
		$member_list = array();
		foreach($member_list_array as $item){
			$member_list[$item['id']] = $item;
		}
		
		$i = 0;
		$num = 0;
		$member1_info = $member2_info = $member3_info = '';
		$recommend_member_info = array();
		while($i < $member_info['relevel']){
			$uid = array_pop($repath);
			if($uid != $member_info['id'] || $member_info['id'] == $order_info['share_uid']){
				$num ++;
				$recommend_member_info[$num] = $member_list[$uid];
			}
			$i++;
		}
		
		$member1_info = isset($recommend_member_info[1]) ? $recommend_member_info[1] : '';
		$member2_info = isset($recommend_member_info[2]) ? $recommend_member_info[2] : '';
		$member3_info = isset($recommend_member_info[3]) ? $recommend_member_info[3] : '';
		
		$left_money = $money;
		
		//直接推荐人
		if($is_income && $member1_info && $member1_info['mobile'] && $member1_info['member_vip_type']){
			$member1_money = mb_number($money * $rem1_money_ratio);
			$member1_integral_money = mb_number($money * $rem1_integral_ratio);
			$member1_integral = $member1_integral_money * $money_integral;
			
			if($member1_money > 0 || $member1_integral > 0){
				$order_save_data['order_rebate'] += ($member1_money + $member1_integral_money);
				
				$log = array();
				$log['type'] = 5;//消费类型 1订单消费 2充值 3提现   4退款 5 收益 6认证消费
				$log['type5_type']=1;//收益类型  1直接推荐人 2间接推荐人 3 间接二级推荐人 4代理区域会员
				$log['order_id'] = $order_info['order_id'];
				$log['des'] = '直接推荐人('.$member_info['member_card'].')消费收益：￥' . $member1_money;
				
				//金额日志
				$this->set_member_balance($member1_info['id'], 1, $member1_money, $log);
				//积分日志
				$log['des'] = '直接推荐人('.$member_info['member_card'].')消费积分：' . $member1_integral;
				$this->set_member_points($member1_info['id'], 1, ($member1_integral), $log);
				
				//收益记录
				$tuijian_data = array();
				$tuijian_data['member_id'] = $member1_info['id'];
				$tuijian_data['order_id'] = $order_info['order_id'];
				$tuijian_data['type'] = 2;
				$tuijian_data['money'] = $member1_money;
				$tuijian_data['integral'] = $member1_integral;
				$tuijian_data['des'] = '直接推荐人('.$member_info['member_card'].')消费收益：￥' . $member1_money . '，消费积分：' . $member1_integral;
				$member_tuijian_data[] = $tuijian_data;
			}
		}
		
		//间接推荐人
		if($is_income && $member2_info && $member2_info['mobile'] && $member2_info['member_vip_type'] > 1){
			$member2_money = mb_number($money * $rem2_money_ratio);
			$member2_integral_money = mb_number($money * $rem2_integral_ratio);
			$member2_integral = $member2_integral_money * $money_integral;
			
			if($member2_money > 0 || $member2_integral > 0){
				$order_save_data['order_rebate'] += ($member2_money + $member2_integral_money);
				
				$log = array();
				$log['type'] = 5;//消费类型 1订单消费 2充值 3提现   4退款 5 收益 6认证消费
				$log['type5_type'] = 2;//收益类型  1直接推荐人 2间接推荐人 3 间接二级推荐人 4代理区域会员
				$log['order_id'] = $order_info['order_id'];
				$log['des'] = '间接推荐人('.$member_info['member_card'].')消费收益：￥' . $member2_money;
				
				//金额日志
				$this->set_member_balance($member2_info['id'], 1, $member2_money, $log);
				//积分日志
				$log['des'] = '间接推荐人('.$member_info['member_card'].')消费积分：' . $member2_integral;
				$this->set_member_points($member2_info['id'], 1, ($member2_integral), $log);
				
				//收益记录
				$tuijian_data = array();
				$tuijian_data['member_id'] = $member2_info['id'];
				$tuijian_data['order_id'] = $order_info['order_id'];
				$tuijian_data['type'] = 3;
				$tuijian_data['money'] = $member2_money;
				$tuijian_data['integral'] = $member2_integral;
				$tuijian_data['des'] = '间接推荐人('.$member_info['member_card'].')消费收益：￥' . $member2_money . '，消费积分：' . $member2_integral;
				$member_tuijian_data[] = $tuijian_data;
			}
		}
		
		//间接二级推荐人
		if($is_income && $member3_info && $member3_info['mobile'] && $member3_info['member_vip_type'] > 1){
			$member3_money = mb_number($money * $rem3_money_ratio);
			$member3_integral_money = mb_number($money * $rem3_integral_ratio);
			$member3_integral = $member3_integral_money * $money_integral;
			
			if($member3_money > 0 || $member3_integral > 0){
				$order_save_data['order_rebate'] += ($member3_money + $member3_integral_money);
				
				$log = array();
				$log['type'] = 5;//消费类型 1订单消费 2充值 3提现   4退款 5 收益 6认证消费
				$log['type5_type'] = 3;//收益类型  1直接推荐人 2间接推荐人 3 间接二级推荐人 4代理区域会员
				$log['order_id'] = $order_info['order_id'];
				$log['des'] = '间接二级推荐人('.$member_info['member_card'].')消费收益：￥' . $member3_money;
				
				//金额日志
				$this->set_member_balance($member3_info['id'], 1, $member3_money, $log);
				//积分日志
				$log['des'] = '间接二级推荐人('.$member_info['member_card'].')消费积分：' . $member3_integral;
				$this->set_member_points($member3_info['id'], 1, ($member3_integral), $log);
				
				//收益记录
				$tuijian_data = array();
				$tuijian_data['member_id'] = $member3_info['id'];
				$tuijian_data['order_id'] = $order_info['order_id'];
				$tuijian_data['type'] = 5;
				$tuijian_data['money'] = $member3_money;
				$tuijian_data['integral'] = $member3_integral;
				$tuijian_data['des'] = '间接二级推荐人('.$member_info['member_card'].')消费收益：￥' . $member3_money . '，消费积分：' . $member3_integral;
				$member_tuijian_data[] = $tuijian_data;
			}
		}
		
		$order_save_data['profit_type'] = $shop_rebate_status;
		$order_save_data['order_profit_all'] = $total_ratio * $money;
		//订单利润 order_profit
		//订单返利金额 order_rebate
		//订单返利总金额 返利池 order_profit_all
		$order_save_data['order_profit'] = $order_save_data['order_profit'] - $order_save_data['order_rebate'];
		M('g_order_info')->where(array('order_id' => $order_info['order_id']))->save($order_save_data);


		if (empty($shop_rebate_status)) {
			$order_goods = M('g_order_goods')->where(array('order_id' => $data_info["order_id"]))->select();
			$member_model = M('member');
			$goods_model = M("g_goods");
			if ($order_goods) {
				foreach ($order_goods as $key => $value) {
					//增加销量
					$goods_model->where(array("goods_id" => $value['goods_id']))->setInc("goods_salesvolume", $value['goods_number']);
				}
			}
		}


		//累计业绩
		if($member_info['member_vip_type'] > 0 && $order_info['is_upgrade'] == 0){
			$yeji_user_ids = $member_info['repath'];
		}else{
			$index_num = strrpos($member_info['repath'], ',');
			$yeji_user_ids = substr($member_info['repath'], 0, $index_num);
		}
		if($syb_money > 0){ //累计创业业绩
			M('member_detail')->where(array('member_id'=>array('in', $yeji_user_ids)))->setInc('syb_yeji', $syb_money);
		}
		if($c_money > 0){ //累计消费业绩
			M('member_detail')->where(array('member_id'=>array('in', $yeji_user_ids)))->setInc('c_yeji', $c_money);
		}
		
		if(!empty($member_tuijian_data)) { //写入收益记录
			$rebate_record_model = M('rebate_record');
			$time = time();
			foreach ($member_tuijian_data as $key => $value) {
				$value['add_time'] = $time;
				$value['status'] = 1;//状态 1用户收益 2 商家返利
				$rebate_record_model->add($value);
			}
		}
		
		$ret['status'] = 1;
		return $ret;
	}


    //业绩   10-13修改只显示已完成的订单 gqh
    public function share()
    {
        /*
       $pre = C('DB_PREFIX');//表前缀
       $where['or_good.share_card'] = $this->member_card;
       $where['ord.order_status'] = 1;
       $where['ord.shipping_status'] = 2;
       //$where['is_attention']=1;
       $p = $_REQUEST['p'];
       $pagesize = 10;
       $p = !empty($p) ? $p : 1;
       $start = ($p - 1) * $pagesize;
       $field = "or_good.*,ord.order_status,ord.shipping_status,ord.pay_status";
       $list = M()->table($pre . 'g_order_goods or_good')//
       ->join($pre . 'g_order_info ord on ord.order_id=or_good.order_id')//
       ->where($where)//
       ->field($field)->limit($start, $pagesize)->order('or_good.rec_id desc')->select();
       foreach ($list as $key => $value) {
           $order_share_status = $this->get_order_share_status($value);
           $list[$key]['code'] = empty($value['share_money']) ? '0' : $value['share_money'];
           $list[$key]['code'] = $order_share_status['code'];
           $list[$key]['code_name'] = $order_share_status['name'];
       }
       if (IS_AJAX) {
           echo json_encode($list);
           die;
       }
       $this->list = $list;
       $count = M()->table($pre . 'g_order_goods or_good')//
       ->join($pre . 'g_order_info order on order.order_id=or_good.goods_id')//
       ->where($where)->count();
       //已支付 已完成
       //$where['or_good.share_card']=$this->member_card;
       $where['ord.pay_status'] = 2;// 支付状态；0，未付款；1，付款中 ；2，已付款
       $where['ord.order_status'] = array('in', '1,4');//订单状态。0，未确认；1，已确 认；2，已取消；3，无效；4，退货；
       $where['ord.shipping_status'] = 2;//商品配送情况，0，未发货； 1，已发货；2，已收货；3，备货中
       $this->count_share = M()->table($pre . 'g_order_goods or_good')//
       ->join($pre . 'g_order_info ord on ord.order_id=or_good.order_id')//
       ->where($where)->count();
       */
        $where['member_id']=$this->uid;
        $p=$_REQUEST['p'];
        $pagesize=10;
        $p=!empty($p)?$p:1;
        $start=($p-1)*$pagesize;
        $type=$_REQUEST['type'];//1积分 0 米值
        $field="*";
        $model=M('member_consume_record');
        $arr=array('1'=>'订单消费','2'=>'充值','3'=>'提现','4'=>'退款','5'=>'收益','6'=>'认证消费','7'=>'系统赠送');
        $where['status']=1;
        $where['type']=5;
        $where['type5_type']=1;//收益类型  1直接推荐人 2间接推荐人 3 间接二级推荐人 4代理区域会员
        $list=$model->where($where)//
        ->field($field)->limit($start,$pagesize)->order('add_time desc')->select();
        //消费类型 1订单消费 2充值 3提现   4退款 5 收益 6认证消费

        if(!empty($list)){
            foreach ($list as $key => $value) {
                $typename=$arr[$value['type']];
                $typename?$typename:'-';
                $list[$key]['typename']=$typename;
                $list[$key]['status']=$value['status']==1?'+':'-';
                $list[$key]['add_time']=date("Y/m/d",$value['add_time']);
            }
        }
        if(IS_AJAX){
            echo json_encode($list);die;
        }
        $this->list=$list;
        $data['balance_all']=sprintf("%.0f",substr(sprintf("%.3f", $data['balance_all']), 0, -3));
        $count=$model->where($where)->sum('money');
        $count=sprintf("%.0f",substr(sprintf("%.3f", $count), 0, -3));
        $this->count_share = $count;
        $this->display();
    }

    //获取订单状态
    public function get_order_share_status($order_info = array())
    {
        if (empty($order_info)) {
            return array();
        }
// pay_status支付状态；0，未付款；1，付款中 ；2，已付款
// shipping_status 商品配送情况，0，未发货； 1，已发货；2，已收货；3，备货中
//order_status订单状态。0，未确认；1，已确 认；2，已取消；3，无效；4，退货；
        $order_status = array('0' => '未确认', '1' => '已确认', '2' => '已取消', '3' => '无效', '4' => '退货');
        $shipping_status = array('0' => '未发货', '1' => '已发货', '2' => '已完成', '3' => '备货中');
        $code = $name = "";
        if ($order_info['order_status'] == 1) {//已确认
            $name = '进行中';
            switch ($order_info['shipping_status']) {
                case '1':
                    $code = "delivered";//已发货
                    break;
                case '2':
                    $code = "received";//已收货
                    $name = "已完成";
                    break;
                default:
                    $code = 'nondelivery';//未发货
                    break;
            }
            return array('code' => $code, 'name' => $name);
        } else {//未确认
            //2已取消；3无效；4，退货；
            if (in_array($order_info['order_status'], array('2', '3', '4'))) {
                if ($order_info['order_status'] == 4) {
                    return array('code' => '', 'name' => '已完成');
                } else {
                    return array('code' => '', 'name' => $order_status[$order_info['pay_status']]);
                }
            } else {////未确认
                if ($order_info['pay_status'] == 2) {//已付款 待确认
                    return array('code' => 'unconfirmed', 'name' => '进行中');
                } else {
                    return array('code' => 'nopay', 'name' => '未付款');
                }
            }
        }

    }

    ///支付
    public function go_pay(){
        $return_data['status'] = 0;
        $order_id = $_REQUEST['order_id'];
        $uid = $this->uid;
        $mem_password = $_REQUEST['mem_password'];
        $pay_type = $_REQUEST['pay_type'];
        $use_balance = $_REQUEST['use_balance'];
        $use_integral = $_REQUEST['use_integral'];
        //购买开关
        $buy_switch = M('sys_param')->where(array('param_code' => 'buy_switch'))->getField('param_value');
        if (empty($buy_switch)) {
            $return_data['error'] = '管理员已关闭交易';
            echo json_encode($return_data);
            die;
        }
        $model_order = D('Mallorder');

        if ($pay_type == "pay_online") {//在线支付
            $save_data = array();
            $save_data['offline'] = 0;//改变订单 货到付款状态
            $res = M('g_order_info')->where(array('order_id' => $order_id))->save($save_data);
            if ($res === false) {
                $return_data['error'] = '支付错误 请刷新页面重试';
                $return_data['status'] = 0;
                echo json_encode($return_data);
                die;
            }
            if($use_balance || $use_integral){
                $this->balance_pay(); //使用余额支付
                die;
            }else{
                $condition = array();
                $condition['order_id'] = $order_id;
                $condition['pay_status'] = '0';// 支付状态；0，未付款；1，付款中 ；2，已付款
                $order_list = $model_order->getOrderList($condition, '', 'order_id,order_sn,order_amount,shipping_fee,surplus,surplus_give,discount_start_time,discount_end_time,discount');
                if (empty($order_list)) {
                    $return_data['error'] = "该订单不存在";
                    echo json_encode($return_data);
                    die;
                }
                ////未使用余额支付
                $_GET['return'] = 1;
                $_GET['pay_sn'] = $order_list[0]['order_sn'];
                $return_data['need_pay'] = 1; //需要支付 1  不需要支付0
                $return_data['status'] = 1;
                echo json_encode($return_data);
                die;
            }
        }
    }

    ///余额支付
    public function balance_pay()
    {
        $return_data['status'] = 0;

        $uid = $this->uid;
        $order_id = $_REQUEST['order_id'];
		$use_balance = $_REQUEST['use_balance'];
        $use_integral = $_REQUEST['use_integral'];
        $mem_password = $_REQUEST['mem_password'];

        if (empty($mem_password)) {
            $return_data['error'] = "密码不能为空";
            echo json_encode($return_data);
            die;
        }
        $member = $this->getMemberInfo();
        if ($member['password'] != md5($mem_password)) {
            $return_data['error'] = "密码错误";
            echo json_encode($return_data);
            die;
        }
        $memberinfo_de = $this->getMemberDetail();
        if (empty($memberinfo_de)) {
            $return_data['error'] = "用户不存在";
            echo json_encode($return_data);
            die;
        }

		//余额
        $balance = $memberinfo_de['balance'] + $memberinfo_de['balance_give'];
        $balance = sprintf("%.2f", substr(sprintf("%.3f", $balance), 0, -2));
        if($balance <= 0 && $use_balance){
            $return_data['error'] = "余额不足";
            echo json_encode($return_data);
            die;
        }
		//积分
		$integral = (int)$memberinfo_de['points']; //账户可用积分
		$integral_left = $memberinfo_de['points'] - $integral;//积分小数部分
		if($integral <= 0 && $use_integral){
			$return_data['error'] = "积分不足";
            echo json_encode($return_data);
            die;
		}

        $model_order = D('Mallorder');
        //重新计算在线支付且处于待支付状态的订单总额
        $condition = array();
        $condition['order_id'] = $order_id;
        $condition['pay_status'] = '0';// 支付状态；0，未付款；1，付款中 ；2，已付款
        $order_list = $model_order->getOrderList($condition, '', 'order_id,order_sn,user_id,order_amount,shipping_fee,is_upgrade,surplus,surplus_give,discount_start_time,discount_end_time,discount,offline,offline_money');
        if (empty($order_list)) {
            $return_data['error'] = "该订单不存在";
            echo json_encode($return_data);
            die;
        }
        //计算本次需要在线支付的订单总金额
        $time = time();
        $pay_amount = 0;
        $offline_money = 0;
        $fee_offline_money = 0;//加运费的货到付款总额
        foreach ($order_list as $order_info) {
            $pay_amount += PriceFormat(floatval($order_info['shipping_fee']));//运费
            ///减去余额支付部分 减去折扣部分
            ///折扣是否过期
            if ($order_info['discount_start_time'] <= $time && $order_info['discount_end_time'] >= $time) {
                $pay_amount += PriceFormat(floatval($order_info['order_amount']) - floatval($order_info['surplus']) - floatval($order_info['discount']));
            } else {
                $pay_amount += PriceFormat(floatval($order_info['order_amount']) - floatval($order_info['surplus']));
            }
            if ($order_info['offline']) {
                $pay_amount -= $order_info['offline_money'];//
            }
        }

        //如果为空，说明已经都支付过了或已经取消或者是价格为0的商品订单，全部返回
        if (empty($pay_amount)) {
            $return_data['error'] = "订单金额为0，不需要支付";
            echo json_encode($return_data);
            die;
        }

        $consume_record_model = M('member_consume_record');
		$integral_model = M('member_integral');
        $member_detail_model = M('member_detail');
        $model_order = M('g_order_info');

        $need_pay = 1;//还需要支付现金
        $m_s_data = array();
        $surplus_give = 0;///支付的赠送余额
		$left_pay_money = $pay_amount;
		$money_to_integral = 10;
		$money = 0;
		//使用余额时扣除余额
		if($use_balance){
			if($left_pay_money <= $balance){//余额足够
				if($memberinfo_de['balance_give'] < $left_pay_money){//赠送余额不足
					$m_s_data['balance_give'] = 0;
					$m_s_data['balance'] = $balance - $pay_amount;
					$surplus_give = $memberinfo_de['balance_give'];
					$money = $pay_amount;
					$left_pay_money = 0;
				}else{//赠送余额足够
					$m_s_data['balance_give'] = mb_number($memberinfo_de['balance_give'] - $pay_amount);
					$m_s_data['balance'] = $memberinfo_de['balance'];
					$surplus_give = $pay_amount;
					$money = $pay_amount;
					$left_pay_money = 0;
				}
			}else{//余额不足
				$m_s_data['balance_give'] = 0;
				$m_s_data['balance'] = 0;
				$surplus_give = $memberinfo_de['balance_give'];
				$money = $balance;
				$left_pay_money -= $balance;
			}
		}

		$points = 0;
		//使用积分支付
		$integral_to_money = 0;
		if($use_integral && $left_pay_money > 0){
			$left_pay_integral = $left_pay_money * $money_to_integral;
			if($left_pay_integral > $integral){ //积分不足
				$m_s_data['points'] = $integral_left;
				$points = $integral;
				$left_pay_money -= ($integral / $money_to_integral);
			}else{ //积分足够
				$m_s_data['points'] = $integral - $left_pay_integral + $integral_left;
				$points = $left_pay_integral;
				$left_pay_money = 0;
			}
			$integral_to_money = ($points/$money_to_integral);
		}
		
		$log_des = '用户使用余额支付：￥'.$money.'；积分支付：￥'.$integral_to_money.'（'.$points.'积分）';
		// if($points > 0){
			// $log_des .= ($money + $integral_to_money) . ' 其中包含'.$points.'积分';
		// }else{
			// $log_des .= $money;
		// }
		
		if($left_pay_money == 0){
			$need_pay = 0;
		}

        $time = time();
        $log = array();
        $log['status'] = 0;//支出
        $log['add_time'] = $time;
        $log['member_id'] = $uid;
        $log['money'] = $money;
        $log['integral'] = $left_pay_integral;
        $log['type'] = 1;
        $log['des'] = $log_des;
		$log['order_id']=$order_id;
        $save_order = array();
        $save_order['surplus'] = $order_list[0]['surplus'] + $money;
        $save_order['surplus_give'] = $order_list[0]['surplus_give'] + $surplus_give;//支付的赠送余额
        $save_order['integral'] = $order_list[0]['integral'] + $points;//支付的积分
        $save_order['integral_money'] = $order_list[0]['integral_money'] + $integral_to_money;//支付的积分相当于的金额
        if (empty($need_pay)) {
            $save_order['pay_status'] = '2';
            $save_order['pay_time'] = $time;
        }
        $member_detail_model->startTrans();//开起事务
        $consume_record_model->startTrans();//开起事务
		$integral_model->startTrans();////开起事务
        $model_order->startTrans();//开起事务
        $m_res = $member_detail_model->where(array('member_id' => $uid))->save($m_s_data);
        $c_res = $consume_record_model->add($log);
		$log['type']=2;//积分type 1，获得 2，消费
		$log['status']=2;//积分status 1，获得 2，消费
		$i_res = $integral_model->add($log);
        $order_res = $model_order->where(array('order_id' => $order_id))->save($save_order);

        //in_array如果设置该参数为 true，则检查搜索的数据与数组的值的类型是否相同。
        if ($m_res !== false && $c_res !== false && $order_res !== false) {
            $return_data['status'] = 1;
            $return_data['need_pay'] = $need_pay;
            $log_msg = '用户使用余额支付￥' . $money . '；积分支付￥'. $integral_to_money.'（'.$points.'积分）';
            if ($need_pay) {//需要继续支付
                $_GET['return'] = 1;
                $_GET['pay_sn'] = $order_list[0]['order_sn'];
                /* $get_pay_url = $this->get_pay_url();
                 if ($get_pay_url['status'] == 1) {
                     $return_data['pay_url'] = $get_pay_url['pay_url'];
                 } else {
                     $return_data['error'] = $get_pay_url['error'];
                     $return_data['status'] = 0;
                 }*/
            } else {//余额  支付完成
                //支付完成 发送短信通知
                $this->order_sendSMS($order_list[0]['order_sn'], $save_order['surplus'], '余额支付');
                //购买成功  查询是否是会员 不是会员则升级为会员
                if ($order_list[0]['is_upgrade']) {//升级订单
                    $member = M('member')->where(array('id' => $order_list[0]['user_id']))->field('id,member_vip_type')->find();
                    if ($member && empty($member['member_vip_type'])) {
                        $reee = M('member')->where(array('id' => $order_list[0]['user_id']))->save(array('member_vip_type' => 1,'vip_time'=>time()));
                        $log_msg .= '升级会员成功';
                    }
                }
            }

            $model_order->commit();//提交事务
            $consume_record_model->commit();//提交事务
            $member_detail_model->commit();//提交事务
            //记录订单日志
            /* if(empty($need_pay)){//订单支付日志
               $data = array();
               $data['order_id'] = $order_id;
               $data['order_amount'] =$money;
                M('g_pay_log')->add($data);
              }*/
            //记录订单日志
            $data = array();
            $data['order_id'] = $order_id;
            $data['log_role'] = 'buyer';
            $data['log_msg'] = $log_msg;
            if (empty($need_pay)) {
                $data['log_orderstate'] = '20';
            } else {
                $data['log_orderstate'] = '10';
            }
            $insert = D('Mallorder')->addOrderLog($data);
        } else {
            $model_order->rollback();//回滚事务
            $consume_record_model->rollback();//回滚事务
            $member_detail_model->rollback();//回滚事务
            $return_data['error'] = "支付失败请稍候再试.";
        }
        echo json_encode($return_data);
        die;
    }


    //订单删除
    public function order_del()
    {
        $return_data['status'] = 0;
        $o_where["order_id"] = array("eq", $_POST["order_id"]);
        $o_where['user_id'] = $this->uid;
        $o_where['user_del'] = 0;
        $data_info = M("g_order_info")->where($o_where)->find();
        if (empty($data_info)) {
            $return_data['error'] = "该订单不存在";
            echo json_encode($return_data);
            die;
        }
        $order_show = $this->get_order_status($data_info);
        if (!in_array($order_show['code'], array('received', 'nopay', 'finish'))) {//已发货
            $return_data['error'] = "订单状态错误";
            echo json_encode($return_data);
            die;
        }
        $order_res = M("g_order_info")->where($o_where)->save(array('user_del' => 1));
        //记录商家日志
        if ($order_res !== false) {
            if ($order_show['code'] == 'nopay' && $data_info['surplus'] > 0) {//未付款 已支付的订单退款 （余额支付）
                $log = array();
                $log['type'] = 4;//消费类型 1订单消费 2充值 3提现   4退款 5 收益 6认证消费
                $log['order_id'] = $data_info['order_id'];
                $log['des'] = '取消订单退余额支付金额：￥' . $data_info['surplus'];
                //加减用户 记录日志  状态 1收入 2支出  如果有赠送余额支付 扣除赠送余额
                $return_data['user_b'] = $this->set_member_balance($data_info['user_id'], 1, $data_info['surplus'], $log, $data_info['surplus_give']);
                if ($return_data['user_b']) {
                    //记录订单日志
                    $data = array();
                    $data['order_id'] = $data_info['order_id'];
                    $data['log_role'] = 'buyer';
                    $data['log_msg'] = '取消订单退余额支付金额：￥' . $data_info['surplus'];
                    $data['log_orderstate'] = '0';
                    $insert = D('Mallorder')->addOrderLog($data);
                }

            } elseif ($order_show['code'] == 'nopay') {
                //记录订单日志
                $data = array();
                $data['order_id'] = $data_info['order_id'];
                $data['log_role'] = 'buyer';
                $data['log_msg'] = '取消订单';
                $data['log_orderstate'] = '0';
                $insert = D('Mallorder')->addOrderLog($data);
            }


            $return_data['code'] = $order_show['code'];
            $return_data['status'] = 1;
            echo json_encode($return_data);
            die;
        } else {
            $return_data['error'] = "操作失败";
            echo json_encode($return_data);
            die;
        }
    }

    ///支付
    public function go_wx_pay(){
        $return_data['status']=0;
        $order_sn=I('order_sn');
        $pay_type=I('pay_type');
        $pay_name = I('pay_name');
        //购买开关
        $buy_switch=M('sys_param')->where(array('param_code'=>'buy_switch'))->getField('param_value');
        if(empty($buy_switch)){
            $return_data['error']='管理员已关闭交易';
            echo json_encode($return_data);die;
        }
        $model_order = D('Mallorder');
        $save_data=array();
        $save_data['pay_name']=$pay_name;//改变订单 支付方式
        $res=M('g_order_info')->where(array('order_sn'=>$order_sn))->save($save_data);
        if($res===false){
            $return_data['error']='支付错误，请刷新页面重试';
            $return_data['status']=0;
            echo json_encode($return_data);die;
        }
        //在线支付
        $condition = array();
        $condition['order_sn'] = $order_sn;
        $condition['pay_status'] = '0';// 支付状态；0，未付款；1，付款中 ；2，已付款
        $order_list = $model_order->getOrderList($condition,'','*');
        if (empty($order_list)) {
            $return_data['error']="该订单不存在";
            echo json_encode($return_data);die;
        }
        //计算本次需要在线支付的订单总金额
        $time=time();
        $pay_amount = 0;
        $offline_money=0;
        foreach ($order_list as $order_info) {
            ///减去余额支付部分 减去折扣部分
            ///折扣是否过期
            if($order_info['discount_start_time']<=$time && $order_info['discount_end_time']>=$time){
                $pay_amount += PriceFormat(floatval($order_info['order_amount']) - floatval($order_info['first_discount'])  - floatval($order_info['surplus']) - floatval($order_info['discount']));
            }else{
                $pay_amount += PriceFormat(floatval($order_info['order_amount']) - floatval($order_info['first_discount']) - floatval($order_info['surplus']));
            }
        }
        //如果为空，说明已经都支付过了或已经取消或者是价格为0的商品订单，全部返回
        if (empty($pay_amount)) {
            $return_data['error']="订单金额为0，不需要支付";
            echo json_encode($return_data);die;
        }
        $pay_sn=$order_list[0]['order_sn'];
        $get_pay_url=$this->get_pay_url($pay_sn,$pay_amount);
        $return_data['need_pay']=1;///需要支付 1  不需要支付0
        if($get_pay_url['status']==1){
            $return_data['status']=1;
            $return_data['pay_url']=$get_pay_url['pay_url'];
        }else{
            $return_data['error']=$get_pay_url['error'];
            $return_data['status']=0;
        }
        echo json_encode($return_data);die;

    }
    ///获取支付链接
    public function get_pay_url($pay_sn = '', $pay_amount = 0)
    {
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        $return = $_GET['return'];
        if (strpos($user_agent, 'MicroMessenger') === false) {
            $data['status'] = 0;
            $data['error'] = '请在微信上打开支付';
            if ($return == 1) {
                return $data;
            }
            echo json_encode($data);
            die;
        }
        $payment_code = 'wxpay';
        if ($payment_code == "wxpay") {
            $user_open_id = $_SESSION['user_open_id'];
            if (empty($user_open_id)) {
                $data['status'] = 0;
                $data['error'] = "拉起支付失败，请刷新页面再试";
                session('user_open_error', null);
                if ($return == 1) {
                    return $data;
                }
                echo json_encode($data);
                die;
            }
            $url = 'pay_sn=' . $pay_sn
                . '&pay_amount=' . $pay_amount
                //    .'&subject='.$order_pay_info['subject']
                . '&openid=' . $user_open_id;

            $url = "http://" . $_SERVER['HTTP_HOST'] . '/api/payment/wpay/get_pay_fenxiao.php?' . $url;
            $data['status'] = 1;
            $data['pay_url'] = $url;
            return $data;
        }

        echo json_encode($data);
        die;
    }



    ///支付宝
    public function go_alipay_pay(){
        $return_data['status']=0;
        $order_sn=I('order_sn');
        $pay_name ='alipay';
        //购买开关
        $buy_switch=M('sys_param')->where(array('param_code'=>'buy_switch'))->getField('param_value');
        if(empty($buy_switch)){
            $return_data['error']='管理员已关闭交易';
            echo json_encode($return_data);die;
        }
        $model_order = D('Mallorder');
        $save_data=array();
        $save_data['pay_name']=$pay_name;//改变订单 支付方式
        $res=M('g_order_info')->where(array('order_sn'=>$order_sn))->save($save_data);
        if($res===false){
            $return_data['error']='支付错误，请刷新页面重试';
            $return_data['status']=0;
            echo json_encode($return_data);die;
        }
        //在线支付
        $condition = array();
        $condition['order_sn'] = $order_sn;
        $condition['pay_status'] = '0';// 支付状态；0，未付款；1，付款中 ；2，已付款
        $order_list = $model_order->getOrderList($condition,'','*');

        if (empty($order_list)) {
            $return_data['error']="该订单不存在";
            echo json_encode($return_data);die;
        }
        //计算本次需要在线支付的订单总金额
        $time=time();
        $pay_amount = 0;
        $offline_money=0;
        foreach ($order_list as $order_info) {
            ///减去余额支付部分 减去折扣部分
            ///折扣是否过期
            if($order_info['discount_start_time']<=$time && $order_info['discount_end_time']>=$time){
                $pay_amount += PriceFormat(floatval($order_info['order_amount']) - floatval($order_info['first_discount'])  - floatval($order_info['surplus']) - floatval($order_info['discount']));
            }else{
                $pay_amount += PriceFormat(floatval($order_info['order_amount']) - floatval($order_info['first_discount']) - floatval($order_info['surplus']));
            }
        }
        //如果为空，说明已经都支付过了或已经取消或者是价格为0的商品订单，全部返回
        if (empty($pay_amount)) {
            $return_data['error']="订单金额为0，不需要支付";
            echo json_encode($return_data);die;
        }
        $return_data['need_pay']=1;///需要支付 1  不需要支付0
        $return_data['status']=1;
        echo json_encode($return_data);die;

    }

}